import { Object3D, Material, Texture, Mesh, Line, Sprite } from 'three'

const disposeMesh = (parent, child) => {
  // 递归释放子节点
  if (child.children.length) {
    const childrenArray = [...child.children]
    childrenArray.forEach(c => disposeMesh(child, c))
  }

  // 释放纹理、材质和几何体
  if (child instanceof Mesh || child instanceof Line || child instanceof Sprite) {
    if (child.material) {
      if (Array.isArray(child.material)) {
        child.material.forEach(m => {
          if (m.map) m.map.dispose()
          m.dispose()
        })
      } else {
        if (child.material.map) child.material.map.dispose()
        child.material.dispose()
      }
    }
    if (child.geometry) {
      child.geometry.dispose()
    }
  } else if (child.material) {
    if (Array.isArray(child.material)) {
      child.material.forEach(m => m.dispose())
    } else {
      child.material.dispose()
    }
  }

  // 从父节点中移除子节点
  parent.remove(child)
}

const getmodle = group => {
  const allChildren = [...group.children]
  allChildren.forEach(child => disposeMesh(group, child))
}

class ResourceTracker {
  constructor() {
    this.resources = new Set()
  }

  track(resource) {
    if (!resource) {
      return resource
    }

    // 处理数组和对象
    if (Array.isArray(resource)) {
      resource.forEach(res => this.track(res))
      return resource
    }

    if (resource.dispose || resource instanceof Object3D) {
      this.resources.add(resource)
    }

    // 递归追踪几何体、材质和子节点
    if (resource instanceof Object3D) {
      this.track(resource.geometry)
      this.track(resource.material)
      this.track(resource.children)
    } else if (resource instanceof Material) {
      for (const value of Object.values(resource)) {
        if (value instanceof Texture) {
          this.track(value)
        }
      }

      if (resource.uniforms) {
        for (const uniform of Object.values(resource.uniforms)) {
          if (uniform) {
            const uniformValue = uniform.value
            if (uniformValue instanceof Texture || Array.isArray(uniformValue)) {
              this.track(uniformValue)
            }
          }
        }
      }
    }

    return resource
  }

  untrack(resource) {
    this.resources.delete(resource)
  }

  dispose() {
    for (const resource of this.resources) {
      if (resource instanceof Object3D && resource.parent) {
        resource.parent.remove(resource)
      }
      if (resource.dispose) {
        resource.dispose()
      }
    }
    this.resources.clear()
  }
}

export { ResourceTracker, getmodle }
